<?php

namespace app\admin\controller\classes;

use app\common\controller\Backend;
use fast\Tree;
/**
 * 
 *
 * @icon fa fa-file
 */
class Leader extends Backend
{
    
    /**
     * Leader模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status"];
    protected $noNeedLogin=["lists","status"];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Leader');
        $this->modelValidate = true;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where);
            $total = $total->where("status", "<>", -1);
            if ($_REQUEST['cid']) {
                $total = $total->where("classes_id", "=", $_REQUEST['cid']);
            }
            $total = $total
                ->count();

            $list = $this->model
                ->where($where);
            if ($_REQUEST['cid']) {
                $list = $list->where("classes_id", "=", $_REQUEST['cid']);
            }
            $list = $list->where("status", "<>", -1)
                ->order('weigh desc,id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();

//            $tree = Tree::instance();
//            $tree->init($list, 'pid');
//            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
//            $data = array();
//            for ($i = 0; $i < count($list); $i++) {
//                $v = $list[$i];
//                $data[] = [
//                    'id' => $v['id'],
//                    'parent' => $v['pid'] ? $v['pid'] : '#',
//                    'name' => $v['name'],
//                    'type' => $v['type'],
//                    'status' => $v['status'],
//                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id'])
//                ];
//            }


            for($i=0;$i<count($list);$i++){
                $list[$i]['leader_id'] = model('User')->getUser_idTextAttr($list[$i]['leader_id']);
                $list[$i]['classes_id']=model('Classes')->getClasses_idTextAttr($list[$i]['classes_id']);
                $list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id']);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
//        $this->assignconfig("relType",$_REQUEST['relType']);
//        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $this->assignconfig("cid", $_REQUEST['cid']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $datatime = date("Y-m-d H:i:s");
                    $params['create_time'] = $datatime;
                    $params['add_time'] = time();
                    $classes_select=model("Classes")->where("id","=",$_REQUEST["cid"])->select();
                    $classes=$classes_select[0];
                    $params['school_id']=$classes['school_id'];
                    $params['classes_id']=$_REQUEST["cid"];
                    $params['leader_id']=$params["leader_id"];
                    $params['status']=1;
                    unset($params['delete_time']);
                    unset($params['update_time']);
                    $nn=$params['leader_id'];
                    for($i=0;$i<count($nn);$i++){
                        $params['leader_id']=$nn[$i];
                        $result = $this->model->insertUpdate($params,["classes_id","leader_id"]);
                    }
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }

                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $add_time=time();
        $this->view->assign("add_time", $add_time);
        $this->view->assign("cid", $_REQUEST['cid']);
        $data=array("args"=>[[],[], []]);
        $leftOptions = $this->generateOptions('/user/user/lists',$data);
        $leftOptions = ($leftOptions==null)?[]:$leftOptions["leftOptions"];
        $rightOptions = $this->generateOptions('/user/user/lists');
        $rightOptions = ($rightOptions==null)?[]:$rightOptions["list"];
        $this->assignconfig("leftOptions", $leftOptions);
        $this->assignconfig("rightOptions", $rightOptions);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $datatime = date("Y-m-d H:i:s");
                    $params['update_time'] = $datatime;
                    unset($params['add_time']);
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    $params['add_time'] = time();
                    $classes_select=model("Classes")->where("id","=",$_REQUEST["cid"])->select();
                    $classes=$classes_select[0];
                    $params['school_id']=$classes['school_id'];
                    $params['classes_id']=$_REQUEST["cid"];
                    $params['leader_id']=$params["leader_id"];

                    $params['status']=1;
                    $nn=$params['leader_id'];
                    for($i=0;$i<count($nn);$i++){
                        $params['leader_id']=$nn[$i];
                        $result = $this->model->insertUpdate($params,["classes_id","leader_id"]);
                    }
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $this->view->assign("row", $row);
        $this->view->assign("cid", $_REQUEST['cid']);
        $data=array("args"=>[explode(",",$row['leader_id']),[], []]);
        $leftOptions = $this->generateOptions('/user/user/lists',$data);
        $leftOptions = ($leftOptions==null)?[]:$leftOptions["leftOptions"];
        $rightOptions = $this->generateOptions('/user/user/lists');
        $rightOptions = ($rightOptions==null)?[]:$rightOptions["list"];
        $this->assignconfig("leftOptions", $leftOptions);
        $this->assignconfig("rightOptions", $rightOptions);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where 1=1";
                if(isset($_REQUEST['city_id'])&&$_REQUEST['city_id']>0){
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql="select id,manager_id name from dev002_gxyusheng.class_leader $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

//        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
//        if (empty($list)&&!empty($r_name)) {
//            $data = array(
//                "type" => "file",
//                "pid" => 0,
//                "name" => $r_name[0]['name']."学科",
//                "title" => $r_name[0]['name'],
//                "ismenu" => 0,
//                "createtime" => time(),
//                "updatetime" => time(),
//                "status" => 1,
//                "school_id" => $_REQUEST['school_id'],
//            );
//            $this->model->create($data);
//        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.class_leader $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
//        $list = db()->query($sql);
//        $tree = Tree::instance();
//        $tree->init($list, 'pid');
//        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.class_leader $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

}
